<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '选择产品',
    navigationStyle: 'custom',
    'app-plus': {
      bounce: 'none',
    },
  },
}
</route>
<template>
  <page-meta :root-font-size="setting.rootFontSize"></page-meta>
  <view style="display: flex; flex-direction: column; background-color: #f2f2f1">
    <wd-sticky>
      <view style="z-index: 9999">
        <wd-navbar :title="`选择产品`" :bordered="false" safeAreaInsetTop>
          <template #left>
            <wd-icon name="thin-arrow-left" size="22px" color="white" @click="goBack"></wd-icon>
          </template>
          <template #right>
            <view style="color: white" @click="submitHandle">确定</view>
          </template>
        </wd-navbar>
      </view>

      <view style="width: 100vw">
        <!-- <wd-col-picker
          label="选择分类"
          label-width="20%"
          v-model="checkvalue"
          :columns="treeQuery"
          value-key="cinvccode"
          label-key="cinvcname"
          :column-change="columnChange"
          @confirm="handleConfirm"
        ></wd-col-picker>
        <view style="width: 90%; height: 1px; margin-left: 5%; background-color: #e3e3e3"></view> -->
        <wd-search
          placeholder="请输入存货名称"
          cancel-txt="搜索"
          @search="searchHandle"
          @cancel="searchHandle"
        >
          <template #prefix>
            <cusPicker
              label=""
              label-width="0%"
              v-model="checkvalue"
              :columns="treeQuery"
              value-key="cinvccode"
              label-key="cinvcname"
              :column-change="columnChange"
              @confirm="handleConfirm"
              use-default-slot
            >
              {{ checkValueName }}
            </cusPicker>

            <!-- <wd-col-picker
              label=""
              label-width="0%"
              placeholder="请选择"
              v-model="checkvalue"
              :columns="treeQuery"
              value-key="cinvccode"
              label-key="cinvcname"
              :column-change="columnChange"
              @confirm="handleConfirm"
              use-default-slot
            >
              {{ checkValueName }}
            </wd-col-picker> -->
          </template>
        </wd-search>
      </view>
    </wd-sticky>
    <view style="margin-top: 20rpx">
      <!-- <wd-card type="rectangle">
        <view class="title" slot="title">
          <view>{{ item.cinvcode }}</view>
        </view>
        <view style="height: 40px" class="content">
          <view>
            <view>{{ item.cinvname }}</view>
            <view>{{ item.cinvstd }}</view>
          </view>
        </view>
      </wd-card> -->
      <template v-for="item in dataList" :key="item.cinvcode">
        <wd-card type="rectangle" @click="clickHandle(item)">
          <template #title>
            <view class="card-title">
              <view style="display: flex; align-items: center; color: #333">
                {{ item.cinvcode }}
              </view>
              <wd-icon
                name="check-outline"
                size="22px"
                color="#0081ff"
                v-if="checkInv && checkInv.cinvcode == item.cinvcode"
              ></wd-icon>
            </view>
          </template>
          <view>
            <view>{{ item.cinvname }}</view>
            <view>{{ item.cinvstd }}</view>
          </view>
        </wd-card>
      </template>
    </view>
    <wd-loadmore :state="loadMore" finishedText="没有更多了" @reload="handleSearch()"></wd-loadmore>
  </view>
</template>
<script lang="ts" setup>
import { useSetting } from '@/stores/setting';
import { getInventoryCategory, getInventoryInfo } from '@/service/pm-requirement';
import cache from '@/utils/cache';
import cusPicker from './component/cusPicker.vue';

const tenantName = cache.get('tenantCode');
const setting = useSetting();
const goBack = () => {
  uni.navigateBack();
};
const page = ref(1);
const size = ref(20);
const loading = ref(false);
const loadMore = ref<any>('finished');
const dataList = ref([]);
const cinvccode = ref('');
const checkInv = ref(null);
onLoad(() => {
  getTree();
});

// 处理数据转换为树形
const transformTree = (data, len = 2, parent = '') => {
  const newTree = [];
  data.map((item) => {
    if (
      (parent &&
        item.cinvccode.substr(0, parent.length) === parent &&
        item.cinvccode.length === Number(len)) ||
      (item.cinvccode.length == len && parent === '')
    ) {
      newTree.push({
        cinvccode: item.cinvccode,
        cinvcname: `(${item.cinvccode})${item.cinvcname}`,
        binvcend: item.binvcend,
        children: transformTree(data, len + 2, item.cinvccode),
      });
    }
  });
  return newTree;
};

const treeQuery = ref([]);
const tabs = ref([]);
const getTree = () => {
  getInventoryCategory({
    tenantCode: tenantName || 'UFDATA_101_2016',
    cinvccodes: '01,02,03',
  })
    .then((res) => {
      if (res.code === 0) {
        const l = transformTree(res.data);

        treeQuery.value = [l];
        console.log(treeQuery.value);

        // const ccode = l[0]['cinvccode'];
        const cinvcname = '全部';
        checkValueName.value = cinvcname;
        // cinvccode.value = ccode;
        getData();
      } else {
        uni.showToast({
          title: res.msg,
          icon: 'none',
        });
      }
    })
    .catch((err) => {
      uni.showToast({
        title: err.msg || err,
        icon: 'none',
      });
    });
};
// 联机
const checkvalue = ref<any[]>([]);
const checkValueName = ref('');

const columnChange = ({ selectedItem, resolve, finish }) => {
  setTimeout(() => {
    if (selectedItem.children && selectedItem.children.length) {
      resolve(selectedItem.children);
    } else {
      // 没有下一项时，执行完成
      finish();
    }
  }, 300);
};

const handleConfirm = (e) => {
  const value = e.value;
  const selectedItems = e.selectedItems;
  checkValueName.value = selectedItems[selectedItems.length - 1]['cinvcname'];
  cinvccode.value = value[value.length - 1];
  refresh();
};

const handleSearch = () => {
  refresh();
};

const cinvcode = ref('');
const cinvname = ref('');
const getData = () => {
  uni.showLoading({
    mask: true,
  });
  loading.value = true;
  loadMore.value = 'loading';
  getInventoryInfo({
    cinvccode: cinvccode.value,
    tenantCode: tenantName || 'UFDATA_101_2016',
    size: size.value,
    current: page.value,
    cinvcode: cinvcode.value,
    cinvname: cinvname.value,
  })
    .then((res) => {
      if (res.code != 0) {
        uni.showToast({
          title: res.msg,
          icon: 'none',
        });
        return;
      }
      dataList.value = dataList.value.concat(res.data.records);
      if (res.data.records.length === size.value) {
        loadMore.value = 'loadEnd';
      } else {
        loadMore.value = 'finished';
      }
    })
    .catch((err) => {
      loadMore.value = 'finished';
      uni.showToast({
        title: err.msg,
        icon: 'none',
      });
    })
    .finally(() => {
      loading.value = false;
      uni.hideLoading();
      uni.stopPullDownRefresh();
    });
};

const refresh = () => {
  dataList.value = [];
  page.value = 1;
  checkInv.value = null;
  getData();
};

const clickHandle = (item) => {
  checkInv.value = item;
};

const submitHandle = () => {
  if (!checkInv.value) {
    uni.showToast({
      title: '请选择一个产品',
      icon: 'none',
      mask: true,
    });
    return;
  }

  uni.$emit('pm-inv', checkInv.value);
  uni.navigateBack();
};

const searchHandle = (e) => {
  // cinvcode.value = e.value;
  cinvname.value = e.value;
  refresh();
};

onPullDownRefresh(() => {
  //重新获取
  refresh();
});
onReachBottom(() => {
  if (loading.value) return;
  // page.value++;
  // getData();
  if (loadMore.value === 'loadEnd') {
    page.value++;
    getData();
  }
});
</script>
<style lang="scss">
:deep(.wd-card__footer) {
  display: none;
}

.card-title {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

:deep(.wd-card__title) {
  width: 100%;
}

:deep(.wd-card__title-content) {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 80rpx !important;
  padding: 0 !important;
}
</style>
